package com.wjy.icu.common.validator;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class DataValidatorImpl implements DataValidator {

    @Autowired
    Validator objValidator;

    @Override
    public <T> void validate(T t) throws Exception {
        log.info("参数：" + t);
        List<String> errors = getErrorMsg(t);

        if (errors != null && errors.size() > 0)
            throw new Exception("错误：校验失败。" + String.join(",", errors));

    }

    @Override
    public <T> boolean isValid(T t) {

        List<String> errors = getErrorMsg(t);

        return (errors != null && errors.size() > 0) ? false : true;

    }

    private <T> List<String> getErrorMsg(T t) {
        Set<ConstraintViolation<T>> set = objValidator.validate(t);
        List<String> errors = new ArrayList<>();

        for (ConstraintViolation<T> constraintViolation : set) {
            errors.add(constraintViolation.getMessage());
        }

        return errors;
    }
}
